<template>
  <div class="app-container">
    <div class="designer" style="height: 100%">
      <div v-if="!showDesigner">
        <!-- 表单管理 -->
        <div style="marginbottom: 20px" class="searchContent">
          <el-input
            v-model="searchText"
            placeholder="请输入表单名称关键字"
            size="small"
            style="width: 260px"
            clearable
          >
          </el-input>
          <div style="marginLeft: 40px">
            <el-button
              type="primary"
              size="small"
              @click="searchChange"
              icon="el-icon-search"
              >搜索</el-button
            >
            <el-button size="small" @click="resetSeach" icon="el-icon-refresh">重置</el-button>
          </div>
        </div>
          <div class="btnList">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="addForm"
              >新增</el-button
            >
            <el-button
              size="small"
              @click="multiDelForm"
              :disabled="multipleSelection.length === 0"
              >批量删除</el-button
            >
            <el-tooltip
              class="item"
              effect="dark"
              content="显隐"
              placement="top"
            >
              <el-button
                icon="el-icon-s-operation"
                circle
                @click="drawer = true"
              ></el-button>
            </el-tooltip>
          </div>
        <el-table
          ref="multipleTable"
          :data="tableData"
          stripe
          style="width: 100%; marginbottom: 20px"
          size="small"
          @selection-change="handleSelectionChange"
          v-loading="tableLoading"
          class="tableInfo"
          row-key="id"
          border
        >
          <el-table-column
            type="selection"
            width="34"
            align="center"
            :reserve-selection="true"
          >
          </el-table-column>
          <el-table-column
            label="序号"
            width="80"
            align="center"
            v-if="!showHideData[0].hide"
          >
            <template slot-scope="scope">
              <span>{{
                scope.$index + (page.pageNo - 1) * page.pageSize + 1
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="formName"
            label="表单名称"
            align="center"
            v-if="!showHideData[2].hide"
          >
          </el-table-column>
          <el-table-column 
            prop="formJsonMessage" 
            label="功能名称" 
            align="center" 
            v-if="!showHideData[1].hide"  
            :formatter="formatName">
          </el-table-column>
          <el-table-column
            prop="creatorName"
            label="创建人"
            align="center"
            v-if="!showHideData[3].hide"
          >
          </el-table-column>
          <el-table-column
            prop="releaseTime"
            label="发布时间"
            align="center"
            v-if="!showHideData[4].hide"
          >
            <template slot-scope="scope">{{
              getDateTime(scope.row.releaseTime)
            }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="177">
            <template slot-scope="scope">
              <el-button size="small" type="text" @click="editForm(scope.row)" icon="el-icon-edit">
                编辑
              </el-button>
              <el-button size="small" type="text" @click="delForm(scope.row)" icon="el-icon-delete" style="color:red">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          :layout="layout"
          :total="pageTotal"
          :page-size="page.pageSize"
          :page-sizes="pageSizes"
          :current-page="page.pageNo"
          style="float: right"
          @size-change="sizeChange"
          @current-change="currentChange"
        >
        </el-pagination>
      </div>
      <!-- 新增--表单发布 -->
      <div v-if="showDesigner">
        <!-- 表单发布顶部 -->
        <el-row :gutter="24" style="border-bottom:1px solid #e8eaec;padding:0 0 10px 0">
          <el-col :span="18">
            <div class="designHeader">
              <div class="designStep">
                <div
                  v-for="(item, index) in steps"
                  :key="index"
                  class="designStepItem"
                >
                  <div
                    class="designStepLine"
                    :style="{
                      border:
                        index > 0
                          ? '1px solid rgba(0,0,0,0.3)'
                          : '1px solid white',
                    }"
                  ></div>
                  <div
                    class="designStepIndex"
                    :style="{
                      background:
                        index < stepNum ? '#409EFF' : 'rgba(0,0,0,0.3)',
                    }"
                  >
                    {{ index + 1 }}
                  </div>
                  <div class="designStepTitle" 
                    :style="{
                      color:
                        index < stepNum ? '#1890FF' : 'rgba(0,0,0,0.3)',
                    }">{{ item }}</div>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="6" style="textAlign: right">
            <el-button v-show="stepNum > 1" @click="nextStep('sub')">上一步</el-button>
            <el-button v-show="stepNum < 3" @click="nextStep('plus')" type="primary">下一步</el-button>
            <el-button v-show="stepNum === 3" type="primary" @click="finishForm">完成</el-button>
            <el-button @click="closeDesign" type="danger" plain>关闭</el-button>
          </el-col>
        </el-row>
        <!-- 步骤1---基础信息 -->
        <div v-show="stepNum === 1" class="base">
          <el-form
            :model="formInfo.basic"
            ref="basicForm"
            label-width="130px"
            class="demo-ruleForm"
          >
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item
                  label="功能编号:"
                  prop="number"
                  :rules="[
                    {
                      required: true,
                      message: '请输入功能编号',
                      trigger: 'blur',
                    },
                    {
                      pattern: /^[0-9]{1,10}$/,
                      message: '请输入长度不超过10的数字',
                      trigger: 'blur',
                    },
                  ]"
                  class="formnum"
                >
                  <el-input
                    v-model="formInfo.basic.number"
                    placeholder="请输入功能编号"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="功能名称:"
                  prop="name"
                  :rules="[
                    {
                      required: true,
                      message: '请输入功能名称',
                      trigger: 'blur',
                    },
                    { validator: funcNameValidator, trigger: 'blur' },
                  ]"
                >
                  <el-input
                    v-model="formInfo.basic.name"
                    placeholder="请输入功能名称"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="上级功能:" prop="superior">
                  <treeselect
                    v-model="formInfo.basic.superior"
                    :options="superior"
                    :normalizer="normalizer"
                    :show-count="true"
                    placeholder="选择上级菜单"
                    :clearable="false"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="表单选择:"
                  prop="typeId"
                  v-show="formInfo.id === ''"
                  :rules="[
                    {
                      required: true,
                      message: '请选择表单',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <treeselect
                    v-model="formInfo.basic.typeId"
                    :options="types"
                    noChildrenText="该分类暂无表单"
                    :disable-branch-nodes="true"
                    :show-count="true"
                    placeholder="选择表单"
                    :clearable="false"
                    @select="formSelect"
                  />
                </el-form-item>
                <el-form-item
                  label="表单选择:"
                  prop="type"
                  v-show="formInfo.id !== ''"
                  :rules="[
                    {
                      required: true,
                      message: '请选择表单选择',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <template v-if="!showChangeForm">
                    <el-input
                      placeholder="请选择表单"
                      v-model="formInfo.basic.type"
                      disabled
                    >
                    </el-input>
                    <!-- <el-input placeholder="请选择表单" v-model="formInfo.basic.type" disabled style="width:90%;marginRight:5px;">
                  </el-input>
                   <el-tooltip class="item" effect="dark" content="更换表单" placement="right">
                    <el-button circle icon="el-icon-refresh" type="primary" @click="changeForm"></el-button>
                   </el-tooltip> -->
                  </template>
                  <treeselect
                    v-else
                    v-model="formInfo.basic.typeId"
                    :options="types"
                    noChildrenText="该分类暂无表单"
                    :disable-branch-nodes="true"
                    :show-count="true"
                    placeholder="选择表单"
                    :clearable="false"
                    @select="formSelect"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item
                  label="功能排序:"
                  prop="sort"
                  :rules="[
                    {
                      required: true,
                      message: '请输入功能排序',
                      trigger: 'blur',
                    },
                    { validator: sortValidator, trigger: 'blur' },
                  ]"
                >
                  <el-input-number
                    v-model="formInfo.basic.sort"
                    placeholder="请输入功能排序"
                    controls-position="right"
                    :min="0"
                    style="width: 100%"
                  >
                  </el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="功能图标:" prop="icon">
                  <el-popover
                    placement="bottom-start"
                    width="460"
                    trigger="click"
                    @show="$refs['iconSelect'].reset()"
                  >
                    <IconSelect ref="iconSelect" @selected="selected" />
                    <el-input
                      slot="reference"
                      v-model="formInfo.basic.icon"
                      placeholder="点击选择图标"
                      readonly
                    >
                      <svg-icon
                        v-if="formInfo.basic.icon"
                        slot="prefix"
                        :icon-class="formInfo.basic.icon"
                        class="el-input__icon"
                        style="height: 32px; width: 16px"
                      />
                      <i
                        v-else
                        slot="prefix"
                        class="el-icon-search el-input__icon"
                      />
                    </el-input>
                  </el-popover>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="是否发布纯表单:" prop="pureForm"> 
                  <el-select
                    v-model="formInfo.basic.pureForm"
                    placeholder="请选择"
                  >
                    <el-option label="否" :value="false" />
                    <el-option label="是" :value="true" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否生成表单链接:" prop="outerChain" v-show="formInfo.basic.pureForm">
                  <el-select
                    v-model="formInfo.basic.outerChain"
                    placeholder="请选择"
                  >
                    <el-option label="否" :value="false" />
                    <el-option label="是" :value="true" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" v-if="false">
              <el-col :span="12">
                <el-form-item label="表单边框:" prop="frame">
                  <el-input
                    v-model="formInfo.basic.frame"
                    placeholder="不填则使用默认宽度   例:50%,500px"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="表单框距顶高度:" prop="high">
                  <el-input
                    v-model="formInfo.basic.high"
                    placeholder="不填则使用默认高度   例:20%,15vh,200px"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="功能描述:" prop="describe">
              <el-input
                type="textarea"
                v-model="formInfo.basic.describe"
                :rows="5"
                maxlength="200"
                show-word-limit
                placeholder="请输入功能描述"
              >
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <!-- 步骤2---查询配置 -->
        <div v-show="stepNum === 2" class="inquire formConfig">
          <el-form ref="step2" :model="tableInquire">
            <el-table
              :data="tableInquire.data.slice((typePage.pageNo - 1) * typePage.pageSize,typePage.pageNo * typePage.pageSize)"
              class="typeTable"
              style="width: 100%; marginbottom: 20px"
              highlight-current-row
              @current-change="handleSelectionChange"
              ref="design"
              row-key="id"
            >
              <el-table-column
                label="序号"
                width="80"
                align="center"
                prop="id"
                v-if="false"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.id }}</span>
                </template>
              </el-table-column>
              <el-table-column
                :render-header="renderHeader"
                align="center"
                width="100"
              >
                <template>
                  <el-form-item>
                    <i class="el-icon-rank" style="fontsize: 16px"></i>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                :render-header="delHeader"
                align="center"
                width="100"
              >
                <template slot-scope="scope">
                  <el-form-item>
                    <i
                      class="el-icon-remove"
                      @click="handleDelete(scope.$index, scope.row)"
                      style="color: #f56c6c; fontsize: 16px"
                    ></i>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="checked"
                align="center"
                width="100"
              >
                <template slot="header" slot-scope="scope">
                  <el-checkbox 
                    :indeterminate="isIndeterminate" 
                    v-model="checkAllDetail"
                    @change="handleCheckAllDetail">启用</el-checkbox>
                </template>
                <template slot-scope="scope">
                  <el-form-item :prop="`data.${scope.$index}.checked`">
                    <el-checkbox v-model="scope.row.checked" @change="handleCheckDetail" :disabled="scope.row.field && fieldParamsMap.get(scope.row.field) ? needDisabledType.includes(fieldParamsMap.get(scope.row.field).tagIcon) : false"></el-checkbox>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="category" label="查询类别" align="center">
                <template slot-scope="scope">
                  <el-form-item :prop="`data.${scope.$index}.category`">
                    <el-select
                      v-model="scope.row.category"
                      @change="
                        () => {
                          scope.row.field = '';
                        }
                      "
                    >
                      <el-option
                        v-for="(item, index) in inquire"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="field" label="字段项名称" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="`data.${scope.$index}.field`"
                    :rules="[
                      { validator: fieldNameValidator2, trigger: 'blur' },
                    ]"
                  >
                    <el-select
                      clearable
                      v-model="scope.row.field"
                      @visible-change="changeValue($event, scope.row.field)"
                    >
                      <el-option
                        v-for="(item, index) in fieldName"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                        :disabled="item.disabled"
                      >
                      </el-option>
                    </el-select>
                    <!-- <el-select
                      clearable
                      v-if="scope.row.category !== 'time'"
                      v-model="scope.row.field"
                      @visible-change="changeValue($event, scope.row.field)"
                    >
                      <el-option
                        v-for="(item, index) in fieldName"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                        :disabled="item.disabled"
                      >
                      </el-option>
                    </el-select> -->
                    <!-- <el-select
                      v-else
                      v-model="scope.row.field"
                      @visible-change="changeTimeValue($event, scope.row.field)"
                    >
                      <el-option
                        v-for="(item, index) in timeConfig"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                        :disabled="item.disabled"
                      >
                      </el-option>
                    </el-select> -->
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="searchType" label="查询方式" align="center">
                <template slot-scope="scope">
                  <el-form-item :prop="`data.${scope.$index}.searchType`">
                    <el-select
                      @change="changesearchType(scope,scope.row)"
                      v-model="scope.row.searchType" :disabled="disabledFunc(scope.row.field)">
                      <el-option
                        v-for="(item, index) in scope.row.field ? optionAssemble(scope.row.field) : searchTypeOptions"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="bindingTime" label="绑定时间字段" align="center">
                <template slot-scope="scope">
                  <el-form-item :prop="`data.${scope.$index}.bindingTime`">
                    <span v-if="scope.row.category!=='time'">不可绑定</span>
                    <span v-else>可绑定</span>
                  </el-form-item>
                </template>
              </el-table-column> -->
            </el-table>
          </el-form>
          <el-pagination
            background
            :layout="layout"
            :total="tableInquire.data.length"
            :page-size="typePage.pageSize"
            :current-page="typePage.pageNo"
            :page-sizes="pageSizes"
            style="float: right"
            @size-change="typeSizeChange"
            @current-change="typeCurrentChange"
          >
          </el-pagination>
        </div>
        <!-- 步骤3---列表配置 -->
        <div v-show="stepNum === 3" class="formConfig">
          <div class="container" style="margin-top: 10px">
            <div class="list-board">
              <el-scrollbar class="list-scrollbar">
                <el-form ref="step3" :model="listConfiguration">
                  <el-table
                    :data="
                      listConfiguration.data.slice(
                        (configPage.pageNo - 1) * configPage.pageSize,
                        configPage.pageNo * configPage.pageSize
                      )
                    "
                    class="configTable"
                    style="width: 100%; marginbottom: 20px"
                    highlight-current-row
                    @current-change="handleSelectionChange"
                    ref="datasource"
                    row-key="id"
                  >
                    <el-table-column
                      label="序号"
                      width="80"
                      align="center"
                      prop="id"
                      v-if="false"
                    >
                      <template slot-scope="scope">
                        <span>{{ scope.row.id }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      :render-header="renderHeader"
                      align="center"
                      width="100"
                    >
                      <template>
                        <el-form-item>
                          <i class="el-icon-rank" style="fontsize: 16px"></i>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      :render-header="addHeader"
                      align="center"
                      width="100"
                    >
                      <template slot-scope="scope">
                        <el-form-item>
                          <i
                            class="el-icon-remove"
                            @click="congigDelete(scope.$index, scope.row)"
                            style="color: #f56c6c; fontsize: 16px"
                          ></i>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="columnName"
                      label="列名"
                      align="center"
                    >
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="`data.${scope.$index}.columnName`"
                          :rules="[
                            { validator: fieldNameValidator, trigger: 'blur' },
                          ]"
                        >
                          <el-select v-model="scope.row.columnName">
                            <el-option
                              v-for="(item, index) in fieldName"
                              :key="index"
                              :label="item.label"
                              :value="item.value"
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="sorting"
                      align="center"
                      width="100"
                    >
                      <template slot="header" slot-scope="scope">
                        <el-checkbox 
                          :indeterminate="isIndeterminateList" 
                          v-model="checkAllDetailList"
                          @change="handleCheckAllDetailList">排序</el-checkbox>
                      </template>
                      <template slot-scope="scope">
                        <el-form-item :prop="`data.${scope.$index}.sorting`">
                          <el-checkbox
                            v-model="scope.row.sorting"
                            @change="handleCheckDetailList"
                          ></el-checkbox>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column prop="align" label="对齐" align="center">
                      <template slot-scope="scope">
                        <el-form-item :prop="`data.${scope.$index}.align`">
                          <el-select v-model="scope.row.align">
                            <el-option
                              v-for="(item, index) in align"
                              :key="index"
                              :label="item.label"
                              :value="item.value"
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="width"
                      label="宽度(单位:px)"
                      align="center"
                    >
                      <template slot-scope="scope">
                        <el-form-item :prop="`data.${scope.$index}.width`">
                          <el-input
                            v-model="scope.row.width"
                            placeholder="请填写列宽，不填写自动分配"
                            clearable
                            onkeyup="this.value=this.value.replace(/[^\d.]/g,``);"
                            maxlength="3"
                          ></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form>
                <el-pagination
                  background
                  :layout="layout"
                  :total="listConfiguration.data.length"
                  :current-page="configPage.pageNo"
                  :page-size="configPage.pageSize"
                  :page-sizes="pageSizes"
                  style="float: right"
                  @size-change="configSizeChange"
                  @current-change="configCurrentChange"
                >
                </el-pagination>
              </el-scrollbar>
            </div>
            <right-panel
              :fieldName="fieldName"
              :rightConfig="rightConfig"
              @syncTreeData="syncTreeData"
              v-if="stepNum === 3"
            ></right-panel>
          </div>
        </div>
      </div>
      <!-- 列显隐 -->
      <el-drawer :visible.sync="drawer" direction="rtl">
        <span slot="title" style="fontSize:18px;font-weight:500;color: #262626;">列显隐</span>
        <el-table
          :data="showHideData"
          size="small"
          border
          style="width: 80%; marginleft: 10%"
        >
          <el-table-column prop="columnName" label="列名" align="center">
          </el-table-column>
          <el-table-column prop="hide" label="隐藏" align="center">
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.hide"></el-checkbox>
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>
    </div>
  </div>
</template>
<script>
import Sortable from "sortablejs";
import { reorganizationParam } from '@/utils/index'
import {
  getPageNoRelease,
  getPageRelease,
  delFormInfo,
  getFormJsonData,
  insertdata,
  updata,
  getDataOneId,
  deletedata,
  getListData,
  menuRelease,
  createBtn,
  deleteBtn,
  getAllMenu,
  menuUpdate,
  multiDel,
  editFormInfo,
  deletepub,
} from "../../../api/custom/formPoster";
import {
  getFormInfo,
  getAllCategory,
  getDelStatus,
  getEditUrl
} from "@/api/custom/formDesigner";
import { getRouters } from "@/api/menu";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";
import RightPanel from "./rightPanel.vue";
import router from '@/router'
import { deepClone } from '../../../utils';
// import Router from 'vue-router'

//菜单发布基本数据初始值
const formInfo1 = {
  id: "", //表单发布id
  basic: {
    number: "", //编码
    name: "", //菜单名称
    superior: 0, //父id
    type: "", //表单名
    typeId: null, //表单Id
    sort: "", //排序
    icon: "", //图标
    frame: "",
    high: "",
    describe: "", //描述
    pureForm: false,
    outerChain: false  //表单链接
  }, //基础信息
};
//右侧面板默认配置
const rightConfig = {
  panelType: "normal", //页面类型
  groupField:'', //分组字段
  sortConfig: {
    field: "", //排序字段
    type: "desc", //排序类型
  },
  paginationConfig: {
    isPag: true, //是否分页
    pageSize: "10条", //分页条数
  },
  colConfig: {
    showIndex: true, //显示序号
    indexName: "序号", //序号名称
    indexSize: 80, //序号宽度
    leftCol: 0, //左固定列
    rightCol: 0, //右固定列
  },
  btnConfig: [
    {
      label: "新增",
      text: "新增",
      method: "insertData",
      position: "table",
      type: "primary",
    },
    {
      label: "编辑",
      text: "编辑",
      method: "editData",
      position: "inline",
      type: "primary",
    },
    {
      label: "删除",
      text: "删除",
      method: "delData",
      position: "inline",
      type: "danger",
    },
  ],
  leftConfig: {
    title: "", //左侧标题
    datasource: "", //数据来源
    table: "", //数据表
    showField: "", //显示字段
    childField: "", //子级字段
    showFieldName: "", //显示字段名字
    dict: "", //数据字典
    dictName: "", //字典名字
    field: "", //关联字段
  },
  panelConfig: [
    {
      title: "", //标题
      icon: "", //图标
      iconColor: "", //图标颜色
      iconBackColor: "", //图标背景色
      backColor: "#fff", //背景色
      field: "", //显示字段
      method: "sum", //计算方式
      unit: "", //单位
    },
  ],
  treeConfig: {
    childrenParams: "",
    parentParams: "",
  },
  tableHeaderConfig: {
    multistage: false,
    treeHeaderData:[]
  }
};
export default {
  components: {
    Treeselect,
    IconSelect,
    RightPanel,
  },
  data() {
    return {
      isEdit: 'new',
      searchFormData: {},
      // 只需精准搜索的类型  下拉、级联、单选、多选、树形、行政区域、用户、部门、岗位
      onlyType: ['my-select', 'my-cascader', 'my-radio-group', 'my-checkbox-group', 'el-tree-select', 'my-region', 'UsersSelector', 'DepartmentSelection', 'PostSelection'],
      searchTypeOptions: [
        {
            label: '等于查询',
            value: 'equals'
        },
        {
            label: '模糊查询',
            value: 'like'
        },
        {
            label: '范围查询',
            value: 'between'
        }
      ],
      isIndeterminate: false, //查询配置未全部选中时， checkbox的不确定状态
      checkAllDetail:false,//查询配置表头选中状态
      isIndeterminateList: false, //列表配置未全部选中时， checkbox的不确定状态
      checkAllDetailList:false,//列表配置表头选中状态
      stepNum: 1, //当前发布步骤
      steps: ["基础信息", "查询配置", "列表配置"], //步骤名称
      //查询类别
      inquire: [
        {
          label: "数据字段查询",
          value: "data",
        },
        // {
        //   label: "时间查询",
        //   value: "time",
        // },
      ],
      timeConfig: [
        {
          label: "创建时间",
          value: "createTime",
        },
      ],
      fieldName: [], //表字段
      //对齐选项
      align: [
        {
          label: "左对齐",
          value: "left",
        },
        {
          label: "右对齐",
          value: "right",
        },
        {
          label: "居中",
          value: "center",
        },
      ],
      //列显隐
      showHideData: [
        {
          columnName: "序号",
          hide: false,
        },
        {
          columnName: "功能名称",
          hide: false,
        },
        {
          columnName: "表单名称",
          hide: false,
        },
        {
          columnName: "创建人",
          hide: false,
        },
        {
          columnName: "创建时间",
          hide: false,
        },
      ],
      drawer: false, //列显隐抽屉
      showDesigner: false, //显示表单设计
      tableLoading: false, //表格加载
      useMenuId: "", //纯表单菜单id
      manageMenuId: "", //表单管理菜单id
      searchText: "", //关键字搜索
      layout: "total,prev, pager, next,sizes,jumper", //分页显示布局
      pageSizes: [10, 20, 30, 50], //分页显示每页条数选择
      pageTotal: 3, //总条数
      page: {
        pageNo: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      },
      typePage: {
        pageNo: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      },
      configPage: {
        pageNo: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      },
      superior: [], //上级功能菜单
      types: [], //表单选择树
      //菜单发布基本数据
      formInfo: {
        id: "", //表单发布id
        basic: {
          number: "", //编码
          name: "", //菜单名称
          superior: 0, //父id
          type: "", //表单名
          typeId: undefined, //表单Id
          sort: "", //排序
          icon: "", //图标
          frame: "",
          high: "",
          describe: "", //描述
          pureForm: false,
          outerChain: false  //表单链接
        }, //基础信息
      },
      tableData: [], //表单发布列表数据
      //查询配置
      tableInquire: {
        data: [],
      },
      //列配置
      listConfiguration: {
        data: [],
      },
      multipleSelection: [], //多选
      formEditData: {}, //表单信息编辑原有字段
      delIds: [], //搜索配置行删除的id
      maxId: 6, //搜索配置行最大id
      delAlign: [], //列配置行删除的id
      maxAlign: 6, //列配置行最大id
      options: [],
      funcName: "", //名称，编辑时备份
      rightConfig: {}, //右侧面板配置
      originBtnConfig: [], //用于做对比的原按钮数组
      isFinish: false, //执行完成操作标识
      showChangeForm: false, //编辑时更换其他表单，当前不支持该功能
      superiorCopy: '', // 初始化时存储上级功能字段
      needDisabledType: ['tuwen', 'password', 'rich-text', 'email', 'switch', 'slider', 'rate', 'color', 'upload', 'lenovoPopup', 'split', 'date-range', 'time-range'], // 需要禁用查询的类型组件
      fieldParamsMap: new Map(), // 存储字段与对应组件信息
      timeStamp: Date.now(),
      // 需要模糊 或者 精准 搜索的类型
      bothType: ['el-input','el-number','el-input-number','getMapPoint'], // 单行文本 多行文本 数字  计数器 编码  地点
      timeType: ['time', 'time-range'],
      dateType: ['date', 'date-range']
    };
  },
  watch: {
    'rightConfig.panelType' (newVal, oldVal) {
        if (newVal === 'tree-list') {
            this.rightConfig.paginationConfig.isPag = false
        } 
        // else {
        //     this.rightConfig.paginationConfig.isPag = true
        // }
    }
  },
  mounted() {
    // 阻止默认行为
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
    this.getList(); //获取已发布表单列表数据
    this.getTreeselect(); //获取菜单树
    // this.remoteMethod(); //获取表单选择树
    this.tableLoading = true;
  },
  methods: {
    changesearchType (e,data) {
      this.tableInquire = JSON.parse(JSON.stringify(this.tableInquire))
      this.timeStamp = Date.now()
    },
    // 部分精准搜索组件和不参与搜索的组件 进行禁用
    disabledFunc (field) {
        if (field) {
            const config = this.fieldParamsMap.get(field)
            if (config) {
              if(config.tag === 'el-date-picker' && config.formatType=== "year"){ //如果是日期组件。且 type 是年的话，没办法范围查询。element ui不支持
                  return true
                }
                if (this.onlyType.includes(config.tag) || this.needDisabledType.includes(config.tagIcon)) {
                    return true
                }
            } else {
                return false
            }
        } else {
            return false
        }
    },
    // 下拉选项组装
    optionAssemble (field) {
        const config = this.fieldParamsMap.get(field)
        if (config) {
            if (this.bothType.includes(config.tag)) {
                return  [
                    {
                        label: '等于查询',
                        value: 'equals'
                    },
                    {
                        label: '模糊查询',
                        value: 'like'
                    },
                ]
            } else if (this.onlyType.includes(config.tag)) {
                return  [
                    {
                        label: '等于查询',
                        value: 'equals'
                    },
                ]
            } else if (this.dateType.includes(config.tagIcon) || this.timeType.includes(config.tagIcon)) {
                if(config.tagIcon === 'date' && config.formatType === 'year'){ //日期组件且type 为年的时候 只能精装查询
                  return [
                    {
                      label: '等于查询',
                      value: 'equals'
                    }
                  ]
                }else{
                  return  [
                    {
                        label: '等于查询',
                        value: 'equals'
                    },
                    {
                        label: '范围查询',
                        value: 'between'
                    },
                  ]
                }
                
            } else {
                return this.searchTypeOptions
            }
        } else {
            return this.searchTypeOptions
        }
    },
    syncTreeData (treeList) {
        this.rightConfig.tableHeaderConfig.treeHeaderData = [...treeList]
    },
    //查询配置两个checkbox点击事件
    handleCheckAllDetail (val) {
      this.isIndeterminate = false
      this.tableInquire.data.forEach(item => {
            // 根据组件类型来确认是否勾选
            const config = this.fieldParamsMap.get(item.field)
            if (this.needDisabledType.includes(config.tagIcon)) {
                item.checked = false
            } else {
                item.checked = val
            }
      })
      this.timeStamp = Date.now()
    },
    handleCheckDetail (val) {
      let totalCount = this.tableInquire.data.length
      let someStatusCount = 0
      this.tableInquire.data.forEach(item => {
          if (item.checked === val) {
              someStatusCount++
          }
      })
      this.checkAllDetail = totalCount === someStatusCount ? val : !val
      this.isIndeterminate = someStatusCount > 0 && someStatusCount < totalCount
    },

    //列表配置两个checkbox点击事件
    handleCheckAllDetailList (val) {
      this.isIndeterminateList = false
      this.listConfiguration.data.forEach(item => {
          item.sorting = val
      })
    },
    handleCheckDetailList (val) {
      let totalCount = this.listConfiguration.data.length
      let someStatusCount = 0
      this.listConfiguration.data.forEach(item => {
          if (item.sorting === val) {
              someStatusCount++
          }
      })
      this.checkAllDetailList = totalCount === someStatusCount ? val : !val
      this.isIndeterminateList = someStatusCount > 0 && someStatusCount < totalCount
    },
    formatName(row, column, cellValue) {
      var statusTxt = ''; 
      return statusTxt = JSON.parse(cellValue).basic.name
    },
    // changeTimeValue(callback, vc) {
    //   if (callback) {
    //     let timedata = this.tableInquire.data.filter(
    //       (_) => _.category == "time"
    //     ); //时间查询
    //     var result = [],
    //       common = [];
    //     for (var i = 0; i < this.timeConfig.length; i++) {
    //       var obj = this.timeConfig[i];
    //       var num = obj.value;
    //       var isExist = false;
    //       for (var j = 0; j < timedata.length; j++) {
    //         var aj = timedata[j];
    //         var n = aj.field;
    //         if (n == num) {
    //           isExist = true;
    //           break;
    //         }
    //       }
    //       if (!isExist) {
    //         obj.disabled = false;
    //         common.push(obj);
    //       } else {
    //         obj.disabled = true;
    //         result.push(obj);
    //       }
    //     }
    //     this.timeConfig = [...common, ...result];
    //   }
    // },
    changeValue(callback, vc) {
      if (callback) {
        if (this.tableInquire.data?.length > 0) {
          let dataList = this.tableInquire.data.filter(
            (_) => _.category == "data"
          );
          var result = [],
            common = [];
          for (var i = 0; i < this.fieldName.length; i++) {
            var obj = this.fieldName[i];
            var num = obj.value;
            var isExist = false;
            for (var j = 0; j < dataList.length; j++) {
              var aj = dataList[j];
              var n = aj.field;
              if (n == num) {
                isExist = true;
                break;
              }
            }
            if (!isExist) {
              obj.disabled = false;
              common.push(obj);
            } else {
              obj.disabled = true;
              result.push(obj);
            }
          }
          this.fieldName = [...common, ...result];
        }
      }
    },
    //获取所有表单分类，并获取各分类下的未发布表单，生成表单选择树
    remoteMethod() {
      getAllCategory()
        .then((res) => {
          if (res.code === 0) {
            let types = res.data.map((item) => {
              return {
                id: -item.id,
                label: item.categoryName,
                children: [],
              };
            });
            getPageNoRelease({
              pageNo: 1,
              pageSize: 10000,
            }).then((res) => {
              res.data.list.map((item) => {
                let formType = types.filter((type) => {
                  return type.id === -item.sysCategory?.id;
                });
                formType[0]?.children.push({
                  id: item.id,
                  label: item.formName,
                  isLeaf: true,
                });
              });
              this.types = types;
            });
          }
        })
        .catch((e) => {
          console.log("获取所有表单分类：", e);
        });
    },
    //更新表单名称值
    formSelect(node) {
      this.formInfo.basic.typeId = node.id
      this.formInfo.basic.type = node.label;
    },
    //多选rowkey
    getRowKeys(row) {
      return row.id;
    },
    // 选择图标
    selected(name) {
      this.formInfo.basic.icon = name;
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      getRouters().then((response) => {
        this.superior = [];
        let menu = {
          id: 0,
          name: "主类目",
          children: [],
        };
        response.data.map((item) => {
          this.changeChildren(item);
        });
        menu.children = response.data;
        this.superior.push(menu);
      });
    },
    //处理树结构children
    changeChildren(item) {
      if (item.children === null) {
        item.children = [];
      } else {
        item.children.map((data) => {
          this.changeChildren(data);
        });
      }
    },
    //更换表单，咱不支持该功能，隐藏掉的
    changeForm() {
      this.$confirm("是否确认更换表单", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.formInfo.basic.type = "";
        this.formInfo.basic.typeId = undefined;
        this.showChangeForm = true;
      });
    },
    //获取已发布表单列表数据
    getList() {
      let params = {
        ...this.page,
        formName: this.searchFormData.name //搜索关键字
      };
      getPageRelease(params)
        .then((res) => {
          if (res.code === 0) {
            this.tableData = res.data.list;

              this.pageTotal = res.data.total;
              this.tableLoading = false;
            }
          })
          .catch((e) => {
            this.tableLoading = false;
          })
    },
    //时间戳格式化
    getDateTime(time) {
      let date = new Date(time);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let hour = date.getHours();
      let minute = date.getMinutes();
      let second = date.getSeconds();
      return `${year}-${month < 10 ? "0" : ""}${month}-${
        day < 10 ? "0" : ""
      }${day}
          ${hour < 10 ? "0" : ""}${hour}:${minute < 10 ? "0" : ""}${minute}:${
        second < 10 ? "0" : ""
      }${second}`;
    },
    //拖拽排序表头
    renderHeader() {
      return <i class="el-icon-sort" style="fontSize:16px;" />;
    },
    //步骤二表头新增
    delHeader() {
      return (
        <span onClick={this.handelAddRow}>
          {" "}
          <i
            class="el-icon-circle-plus"
            style="color:#409EFF;fontSize:16px;"
          />{" "}
        </span>
      );
    },
    //步骤2新增一条数据
    handelAddRow() {
        if (this.fieldName.length === this.tableInquire.data.length) {
            this.$message.warning('没有可新增的字段')
            return
        }
        let num = 0;
        if (this.delIds.length > 0) {
            num = this.delIds[0];
            this.delIds.splice(0, 1);
        } else {
            num = this.maxId + 1;
            this.maxId = num;
        }
        var obj = {
            id: num,
            checked: false,
            category: "",
            field: "",
            searchType: 'like',
            bindingTime: "不可绑定",
        };
        this.tableInquire.data.unshift(obj);
    },
    //步骤三表头新增
    addHeader() {
      return (
        <span onClick={this.formAddRow}>
          {" "}
          <i
            class="el-icon-circle-plus"
            style="color:#409EFF;fontSize:16px;"
          />{" "}
        </span>
      );
    },
    //步骤3新增一条数据
    formAddRow() {
      let num = 0;
      if (this.delAlign.length > 0) {
        num = this.delAlign[0];
        this.delAlign.splice(0, 1);
      } else {
        num = this.maxAlign + 1;
        this.maxAlign = num;
      }
      var list = {
        id: num,
        columnName: "",
        sorting: false,
        align: "",
        width: "",
      };
      this.listConfiguration.data.push(list);
    },
    //步骤二行拖拽
    rowDrop() {
      const tbody = document.querySelector(
        ".typeTable .el-table__body-wrapper tbody"
      );
      const _this = this;
      Sortable.create(tbody, {
        draggable: ".el-table__row",
        onEnd({ newIndex, oldIndex }) {
          //回调
          const currRow = _this.tableInquire.data.splice(oldIndex, 1)[0];
          _this.tableInquire.data.splice(newIndex, 0, currRow);
        },
      });
    },
    //步骤三行拖拽
    rowDrop2() {
      const tbody = document.querySelector(
        ".configTable .el-table__body-wrapper tbody"
      );
      const _this = this;
      Sortable.create(tbody, {
        draggable: ".el-table__row",
        onEnd({ newIndex, oldIndex }) {
          //回调
          const currRow = _this.listConfiguration.data.splice(oldIndex, 1)[0];
          _this.listConfiguration.data.splice(newIndex, 0, currRow);
        },
      });
    },
    //步骤二删除一条数据
    handleDelete(index, row) {
      const _this = this;
      this.$confirm("是否确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          _this.delIds.push(row.id);
          return _this.tableInquire.data.splice(
            index + (_this.typePage.pageNo - 1) * _this.typePage.pageSize,
            1
          );
        })
        .then((data) => {
          this.$message.success("删除成功");
          // 返回到原记录所在页面，而当原记录所在页不存在时，则返回上一页
          if (
            _this.typePage.pageNo > 1 &&
            _this.tableInquire.data.length <=
              (_this.typePage.pageNo - 1) * _this.typePage.pageSize
          ) {
            _this.typePage.pageNo--;
          }
        });
    },
    //步骤三删除一条数据
    congigDelete(index, row) {
      const _this = this;
      this.$confirm("是否确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          _this.delAlign.push(row.id);
          return _this.listConfiguration.data.splice(
            index + (_this.configPage.pageNo - 1) * _this.configPage.pageSize,
            1
          );
        })
        .then((data) => {
          this.$message.success("删除成功");
          // 返回到原记录所在页面，而当原记录所在页不存在时，则返回上一页
          if (
            _this.configPage.pageNo > 1 &&
            _this.listConfiguration.data.length <=
              (_this.configPage.pageNo - 1) * _this.configPage.pageSize
          ) {
            _this.configPage.pageNo--;
          }
        });
    },
    //多选，数据选择改变
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //表单管理---编辑，获取表单发布数据赋值
    editForm(row) {
      this.isEdit = 'edit'
      this.formEditData = JSON.parse(row.formJsonMessage);
      this.formInfo.id = row.id;
      this.formInfo.basic = JSON.parse(JSON.stringify(this.formEditData.basic));
      this.funcName = this.formInfo.basic.name;
      this.superiorCopy = deepClone(this.formInfo.basic.superior)
      this.tableInquire.data = this.formEditData.searchConfig;
      const allComp = JSON.parse(row.formJsonUser).fields
      this.setFieldMap(allComp)
      let num =0
      this.tableInquire.data.forEach((item,index)=>{
        if(item.checked){
          num++
        }
      })
      this.setType()
      //确定点击编辑进去界面时查询配置表头checkbox是否要选中
      this.isIndeterminate = num > 0 && num < this.tableInquire.data.length
      this.checkAllDetail = (num === this.tableInquire.data.length)
      this.listConfiguration.data = this.formEditData.alignConfig;
      let Num =0
      this.listConfiguration.data.forEach((item,index)=>{
        if(item.sorting){
          Num++
        }
      })
      //确定点击编辑进去界面时列表配置表头checkbox是否要选中
      this.isIndeterminateList = Num > 0 && Num < this.listConfiguration.data.length
      this.checkAllDetailList = (Num === this.listConfiguration.data.length)
      if (!this.formEditData.rightConfig.treeConfig) {
        this.formEditData.rightConfig.treeConfig = {
          childrenParams: "",
          parentParams: "",
        };
      }
      if (!this.formEditData.rightConfig.tableHeaderConfig) {
        this.formEditData.rightConfig.tableHeaderConfig = {
            multistage: false,
            treeHeaderData:[]
        }
      }
      this.rightConfig = { ...this.formEditData.rightConfig };
      this.originBtnConfig = JSON.parse(
        JSON.stringify(this.formEditData.rightConfig.btnConfig)
      );
      this.maxId = this.formEditData.maxId;
      this.maxAlign = this.formEditData.maxAlign;
      this.delAlign = this.formEditData.delAlign;
      this.delIds = this.formEditData.delIds;
      this.manageMenuId = row.manageMenuId;
      this.useMenuId = row.useMenuId;
      this.showChangeForm = false;
      this.showDesigner = true;
      this.oldJson = JSON.parse(row.formJsonMessage);
    },
    // 组装字段与属性的map
    setFieldMap (list) {
        list.forEach((curComp,index) => {
            if (['Steps', 'el-card','el-tabs','Steps', 'el-collapse', 'Subform'].includes(curComp.__config__.tag)) {
                //布局组件，遍历内部子组件
                const newList = curComp.__config__.children
                for (const item of newList) {
                    this.setFieldMap(item.__config__.children)
                }
            } else {
              if(curComp.__config__.tag === 'el-date-picker'){ //日期选择
                curComp.__config__.formatType = curComp.type
                this.fieldParamsMap.set(curComp.__vModel__, curComp.__config__)
                if (curComp.type === 'year' && curComp.__config__.tagIcon == 'date') { //日期选择为年  只能是等于查询
                  if(this.tableInquire.data[index]){
                    this.tableInquire.data[index].searchType = 'equals'
                  }
                }
              } else{
                this.fieldParamsMap.set(curComp.__vModel__, curComp.__config__)
              }
            }
        })
    },
    setType () {
        this.tableInquire.data.forEach((item,index)=>{
            const config = this.fieldParamsMap.get(item.field)
            if (config) {
                if (!item.searchType) {
                    if (this.bothType.includes(config.tag)) {
                        item.searchType = 'like'
                    } else if (this.onlyType.includes(config.tag) || this.timeType.includes(config.tagIcon)) {
                        item.searchType = 'equals'
                    } else if (this.dateType.includes(config.tagIcon)) {
                      if(config.tagIcon == 'date' || config.tagIcon == 'time'){  // 日期选择 时间选择默认 精确
                        item.searchType = 'equals'
                      }else{
                        item.searchType = 'between'
                      }
                    } else {
                        item.searchType = ''
                    }
                }
                if (this.needDisabledType.includes(config.tagIcon)) {
                    item.checked = false
                    item.searchType = ''
                } else if ( this.isEdit == 'new' && (index === 0 || index === 1)) { //编辑 启用不默认勾选
                    // 保留之前 前两个字段 选中 逻辑
                    item.checked = true
                } else {
                    // 处理历史数据
                    if (item.checked === undefined) {
                        item.checked = false
                    }
                }
            }
        })
    },
    //删除表单发布
    delForm(row) {
      this.$confirm("是否确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return delFormInfo(row.id);
        })
        .then((res) => {
          if (res.code === 0) {
            this.$message.success("删除成功");
            // 菜单变化
            this.getList();
            this.$store.dispatch("GenerateRoutes").then((per) => {
                // router.addRoutes(per)
            });
          }
        })
        .catch((e) => console.log("删除表单信息:", e));
    },
    //批量删除表单发布
    multiDelForm() {
      this.$confirm("是否确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let ids = this.multipleSelection.map((item) => {
          return item.id;
        });
        multiDel(ids)
          .then((res) => {
            if (res.code === 0) {
              this.$message.success(res.data);
              // 菜单变化
              this.getList();
              this.$store.dispatch("GenerateRoutes").then((per) => {
                // router.addRoutes(per)
              });
            } else {
              this.$message.error("所选数据删除失败！");
            }
          })
          .catch((e) => console.log("批量删除：", e));
      });
    },
    //新增表单发布，显示表单发布设计页面
    addForm() {
      this.isEdit = 'new'
      this.showDesigner = true;
      this.showChangeForm = false;
      this.remoteMethod()
      this.rightConfig = JSON.parse(JSON.stringify(rightConfig)); //默认右侧面板配置
      this.formInfo = JSON.parse(JSON.stringify(formInfo1));
      // this.resetStep2()
      // this.resetStep3()
    },
    //菜单发布
    publishMenu(data, dataManage) {
      menuRelease(data)
        .then((res) => {
          if (res.code === 0) {
            this.useMenuId = res.data;
          }
        })
        .catch((e) => console.log(e));

      menuRelease(dataManage)
        .then((res) => {
          if (res.code === 0) {
            this.manageMenuId = res.data;
            const btnParam = this.rightConfig.btnConfig.map((item) => {
              return {
                name: item.label,
                permission: "curreny",
                type: 3,
                sort: this.formInfo.basic.sort + 2,
                parentId: res.data,
                status: 0,
                label: item.label,
              };
            });
            createBtn(btnParam).then((res) => {
            });
          }
        })
        .catch((e) => console.log(e));
    },
    publishPureMenu(dataManage) {
      // menuRelease([dataManage])
      menuRelease(dataManage)
        .then((res) => {
          if (res.code === 0) {
            this.manageMenuId = res.data;
            const btnParam = this.rightConfig.btnConfig.map((item) => {
              return {
                name: item.label,
                permission: "curreny",
                type: 3,
                sort: this.formInfo.basic.sort + 2,
                parentId: res.data,
                status: 0,
                label: item.label,
              };
            });
            createBtn(btnParam).then((res) => {
            });
          }
        })
        .catch((e) => console.log(e));
    },
    publishPureFromMenu(data) {
      alert(1)
      // menuRelease([data])
      menuRelease(data)
        .then((res) => {
          if (res.code === 0) {
            this.useMenuId = res.data;
          }
        })
        .catch((e) => console.log(e));
    },
    //更新菜单
    updateMenu(data, dataManage) {
      //用户提交菜单
      menuUpdate(data)
        .then((res) => {
          if (res.code === 0) {
          }
        })
        .catch((e) => console.log(e));
      //管理菜单
      menuUpdate(dataManage)
        .then((res) => {
          if (res.code === 0) {
          }
        })
        .catch((e) => console.log(e));
    },
    updatePureMenu(data) {
      //用户提交菜单
      menuUpdate(data)
        .then((res) => {
          if (res.code === 0) {
          }
        })
        .catch((e) => console.log(e));
    },
    //表单发布完成
    finishForm() {
      if (this.isFinish) {
        return;
      }
      this.isFinish = true; //当前执行完成操作
      this.$refs.step3.validate((validate) => {
        //校验步骤三数据
        if (validate) {
          // 是否生成外链
          let dataUrl = {
            id:  this.formInfo.basic.typeId,
            outerChain: this.formInfo.basic.outerChain,
            path:
             this.formInfo.basic.superior === 0
              ? `/form/submit/${this.formInfo.basic.name}/${this.formInfo.basic.typeId}`
              : `submit/${this.formInfo.basic.typeId}`,
          }
          getEditUrl(dataUrl).then((res) => {
          })
          //表单发布基本信息和配置
          let job = {
            basic: this.formInfo.basic, //基本信息
            searchConfig: this.tableInquire.data, //搜索配置
            alignConfig: this.listConfiguration.data, //列配置
            rightConfig: this.rightConfig, //右侧面板配置
            maxId: this.maxId,
            maxAlign: this.maxAlign,
            delIds: this.delIds,
            delAlign: this.delAlign,
          };
          //纯表单页面菜单参数
          let data = {
            component: "custom/formdesign/components/formSubmit",
            icon: this.formInfo.basic.icon,
            name: this.formInfo.basic.name,
            parentId: this.formInfo.basic.superior,
            path:
              this.formInfo.basic.superior === 0
                ? `/form/submit/${this.formInfo.basic.name}/${this.formInfo.basic.typeId}`
                : `submit/${this.formInfo.basic.typeId}`,
            permission: "",
            sort: this.formInfo.basic.sort,
            status: 0,
            type: 2,
          };
          //表单管理页面菜单参数
          let dataManage = {
            component: "custom/formPost/formManage",
            icon: this.formInfo.basic.icon,
            name: this.formInfo.basic.pureForm ? this.formInfo.basic.name + "管理" :  this.formInfo.basic.name, // 否 -- 只显示名称
            parentId: this.formInfo.basic.superior,
            path:
              this.formInfo.basic.superior === 0
                ? `/form/manage/${this.formInfo.basic.name}管理/${this.formInfo.basic.typeId}`
                : `manage/${this.formInfo.basic.typeId}`,
            permission: "",
            sort: this.formInfo.basic.sort,
            status: 0,
            type: 2,
          };
          // const btnParam=this.rightConfig.btnConfig.map(item=>{
          //   return {
          //     name:item.label,
          //     permission: "curreny",
          //     type:3,
          //     sort: this.formInfo.basic.sort + 2,
          //     parentId: this.formInfo.basic.superior,
          //     status: 0,
          //   }
          // })
          if (!this.formInfo.id) {
            //新增
            this.formInfo.basic.pureForm
              ? this.publishMenu(data, dataManage)
              : this.publishPureMenu(dataManage); // 是否发布纯表单
            let timer = setInterval(() => {
              if (this.useMenuId || this.manageMenuId) {
                clearInterval(timer);
                //表单发布信息
                let params = {
                  id: this.formInfo.basic.typeId, //表单id
                  formJsonMessage: JSON.stringify(job), //表单发布配置
                  useMenuId: this.useMenuId, //纯表单菜单id
                  manageMenuId: this.manageMenuId, //管理菜单id
                  isReference: 1, //已发布，已引用
                  releaseTime: new Date(), //发布时间
                };
                //修改表单信息
                editFormInfo(params)
                  .then((res) => {
                    if (res.code === 0) {
                      this.$message.success("表单发布保存成功");
                      this.page.pageNo = 1;
                      this.searchText = "";
                      this.tableLoading = true;
                      this.$store.dispatch("GenerateRoutes").then((per) => {
                            router.addRoutes([...per])
                            this.closeDesign();
                            this.$nextTick(() => {
                                this.getList();
                                this.$refs.multipleTable.clearSelection();
                            })
                      });
                    }
                  })
                  .catch((e) => console.log(e));
              }
            }, 1000);
          } else {
            //编辑修改表单发布
            data.id = this.useMenuId;
            dataManage.id = this.manageMenuId;
           
           //判断是否有发布纯表单页面
            if(this.useMenuId){ //有
              //获取纯表单是否被删除状态值
              let params ={
                id:this.useMenuId
              }
              getDelStatus(params).then(res=>{
                console.log(res.data,'获取纯表单是否被删除状态值')
                if(res.data){
                  //未删除
                  // if(this.useMenuId){
                    //纯表单id存在---已有纯表单
                    if(this.formInfo.basic.pureForm){
                      console.log("未删除，要发布纯表单")
                      menuUpdate(data).then((res) => {
                        if (res.code === 0) {
                          let params = {
                            id: this.formInfo.basic.typeId,
                            formJsonMessage: JSON.stringify(job),
                          };
                          editFormInfo(params).then((res) => {
                                if (res.code === 0) {
                                // this.$message.success("修改成功");
                                // this.tableLoading = true;
                                this.$store.dispatch("GenerateRoutes").then((per) => {
                                    if (this.superiorCopy !== this.formInfo.basic.superior) {
                                        router.addRoutes([...per])
                                    }
                                    this.closeDesign();
                                    this.$nextTick(() => {
                                        this.$refs.multipleTable.clearSelection();
                                        // 菜单变化
                                        this.getList();
                                    })
                                });
                            }
                          }).catch((e) => console.log(e));
                        }
                      }).catch((e) => console.log(e));
                    }else{
                      console.log("未删除，不要发布纯表单")
                      //删除纯表单
                      deletepub(this.useMenuId).then(res=>{
                      })
                    }
                }else{
                  //纯表单被删除
                  if(this.formInfo.basic.pureForm){
                    // publishPureFromMenu(data)  //发布新的纯表单页
                    console.log('纯表单被删除,并发布新的纯表单页')
                    menuRelease(data)
                      .then((res) => {
                        if (res.code === 0) {
                          this.useMenuId = res.data;
                          // let params = {
                          //   id: this.formInfo.basic.typeId,  //表单id
                          //   useMenuId: this.useMenuId, //纯表单菜单id
                          //   formJsonMessage: JSON.stringify(job),
                          // };
                          let temp = JSON.parse(JSON.stringify(this.formInfo.basic))
                          let params = {
                            id: temp.typeId,  //表单id
                            useMenuId: this.useMenuId, //纯表单菜单id
                            formJsonMessage: JSON.stringify(job),
                          };
                          editFormInfo(params)
                            .then((res) => {
                              if (res.code === 0) {
                                // this.$message.success("修改成功");
                                // this.tableLoading = true;
                                this.$store.dispatch("GenerateRoutes").then((per) => {
                                    router.addRoutes([...per])
                                    this.closeDesign();
                                    this.$nextTick(() => {
                                        this.$refs.multipleTable.clearSelection();
                                        // 菜单变化
                                        this.getList();
                                    })
                                });
                              }
                            })
                            .catch((e) => console.log(e));
                        }
                      })
                      .catch((e) => console.log(e));
                    
                  }
                }
              })
            }else{
              //是否要发布纯表单页面
              if(this.formInfo.basic.pureForm){ //是
                console.log('未发布纯表单,要发布新的纯表单页')
                menuRelease(data)
                  .then((res) => {
                    if (res.code === 0) {
                      this.useMenuId = res.data;
                      let temp = JSON.parse(JSON.stringify(this.formInfo.basic))
                      let params = {
                        id: temp.typeId,  //表单id
                        useMenuId: this.useMenuId, //纯表单菜单id
                        formJsonMessage: JSON.stringify(job),
                      };
                      editFormInfo(params)
                        .then((res) => {
                          if (res.code === 0) {
                            // this.$message.success("修改成功");
                            // this.tableLoading = true;
                            this.$store.dispatch("GenerateRoutes").then((per) => {
                                router.addRoutes(per)
                                this.closeDesign();
                                this.$nextTick(() => {
                                    this.$refs.multipleTable.clearSelection();
                                    // 菜单变化
                                    this.getList();
                                })
                            });
                          }
                        })
                        .catch((e) => console.log(e));
                    }
                  })
                  .catch((e) => console.log(e));
              }
            }
            //获取管理页是否被删除状态值
            let Params = {
              id: this.manageMenuId,
            };
            getDelStatus(Params).then((res) => {
              if (res.data) {
                //未删除
                // 判断按钮是否有新增、删除、修改操作,然后先删除再新增
                if(JSON.stringify(this.originBtnConfig) !==JSON.stringify(this.rightConfig.btnConfig)) {
                  const params = {
                    id: this.manageMenuId,
                  };
                  deleteBtn(params).then((res) => {
                    if (res.data) {
                      const btnParam = this.rightConfig.btnConfig.map(
                        (item) => {
                          return {
                            name: item.label,
                            permission: "curreny",
                            type: 3,
                            sort: this.formInfo.basic.sort + 2,
                            parentId: params.id,
                            status: 0,
                            label: item.label,
                          };
                        }
                      );
                      createBtn(btnParam).then((res) => {
                      });
                    }
                  });
                }
                //更新管理菜单
                menuUpdate(dataManage)
                  .then((res) => {
                    if (res.code === 0) {
                      let params = {
                        id: this.formInfo.basic.typeId,
                        formJsonMessage: JSON.stringify(job),
                      };
                      editFormInfo(params)
                        .then((res) => {
                          if (res.code === 0) {
                            this.$message.success("修改成功");
                            this.$store.dispatch("GenerateRoutes").then((per) => {
                                if (this.superiorCopy !== this.formInfo.basic.superior) {
                                    router.addRoutes([...per])
                                }
                                this.closeDesign();
                                this.$nextTick(() => {
                                    this.getList();
                                    this.$refs.multipleTable.clearSelection();
                                })
                            });
                            
                          }
                        })
                        .catch((e) => console.log(e));
                    }
                  })
                  .catch((e) => console.log(e));
              } else {   
                // 管理菜单被删除，重新创建并发布
                menuRelease(dataManage)
                  .then((res) => {
                    if (res.code === 0) {
                      this.manageMenuId = res.data;
                      // let temp = JSON.parse(JSON.stringify(this.formInfo.basic))
                      // let tempId = res.data
                      const btnParam = this.rightConfig.btnConfig.map((item) => {
                        return {
                          name: item.label,
                          permission: "curreny",
                          type: 3,
                          sort: this.formInfo.basic.sort + 2,
                          parentId: res.data,
                          status: 0,
                          label: item.label,
                        };
                      });
                      let params = {
                        id:this.formInfo.basic.typeId,  //表单id
                        manageMenuId: this.manageMenuId, //管理菜单id
                        formJsonMessage: JSON.stringify(job),
                      };
                      editFormInfo(params)
                        .then((res) => {
                          if (res.code === 0) {
                            this.$message.success("修改成功");
                            // this.tableLoading = true;
                            this.$store.dispatch("GenerateRoutes").then((per) => {
                                router.addRoutes(per)
                                this.closeDesign();
                                this.$nextTick(() => {
                                    this.$refs.multipleTable.clearSelection();
                                    // 菜单变化
                                    this.getList();
                                })
                            });
                          }
                        })
                        .catch((e) => console.log(e));
                      createBtn(btnParam).then((res) => {  
                        
                      });
                    }
                  })
                  .catch((e) => console.log(e));
                
              }
            });

            //删除并发布管理页
            // deletepub(dataManage.id ? dataManage.id : 0).then((res) => {
            //   if(res.code === 0){
            //     
            //     // 重新发布管理页
            //     this.publishPureMenu(dataManage)

            // 1. 删除表单   是 -- 发布2个页面  否  -- 只发布管理页
            //     deletepub(data.id ? data.id : 0).then((res) => {
            //     // if(res.code === 0){
            //         if(res.code === 0){
            //            //2. 根据 是否创建表单this.formInfo.basic.pureForm 否 -- false  是 -true
            //             if(this.formInfo.basic.pureForm ){ // 是 -- 创建纯表单
            //                     menuRelease(data)    //创建
            //                       .then((res) => {
            //                         if (res.code === 0) {
            //                           this.useMenuId = res.data
            //                           data.id = res.data
            //                                 let params = {    // 3. 修改表单信息
            //                                 id: this.formInfo.basic.typeId,
            //                                 formJsonMessage: JSON.stringify(job),
            //                                 useMenuId: res.data, //纯表单菜单id
            //                               };
            //                               editFormInfo(params)
            //                                 .then((res) => {
            //                                   if (res.code === 0) {
            //                                     this.$message.success("修改成功");
            //                                     this.closeDesign();
            //                                     this.$refs.multipleTable.clearSelection();
            //                                     // 菜单变化
            //                                     this.getList();
            //                                     this.$store.dispatch('GenerateRoutes').then(per => {})
            //                                   }
            //                                 })
            //                                 .catch((e) => console.log(e));
            //                         }
            //                       })
            //                       .catch((e) => console.log(e));
            //             }else{
            //               let params = {    // 3. 修改表单信息
            //                 id: this.formInfo.basic.typeId,
            //                 formJsonMessage: JSON.stringify(job),
            //                 useMenuId:  0
            //               };
            //               editFormInfo(params)
            //                 .then((res) => {
            //                   if (res.code === 0) {
            //                     this.$message.success("修改成功");
            //                     this.closeDesign();
            //                     this.$refs.multipleTable.clearSelection();
            //                     // 菜单变化
            //                     this.getList();
            //                     this.$store.dispatch('GenerateRoutes').then(per => {})
            //                   }
            //                 })
            //                 .catch((e) => console.log(e));
            //             }

            //           // }
            //   }
            // })
            //   }
            // })
          }
        } else {
          this.isFinish = false;
          this.$message.error("列名重复，请修改");
          return false;
        }
      });
    },
    //关闭表单发布设计，重置、清空变量
    closeDesign() {
      this.useMenuId = "";
      this.manageMenuId = "";
      this.showDesigner = false;
      this.stepNum = 1;
      this.fieldName = [];
      this.$refs.basicForm.resetFields();
      this.options = [];
      this.formInfo.id = "";
      this.isFinish = false;
    },
    //根据表字段初始化步骤二数据
    resetStep2() {
      this.tableInquire.data = this.fieldName.map((item, index) => {
        return {
          id: index,
          checked: index == 0 || index == 1 ? true : false,
          category: "data",
          field: item.value,
          bindingTime: "不可绑定",
          disabled: false,
        };
      });
      this.setType()
      this.maxId = this.fieldName.length - 1;
      this.delIds = [];
    },
    //根据表字段初始化步骤三数据
    resetStep3() {
      this.listConfiguration.data = this.fieldName.map((item, index) => {
        return {
          id: index,
          columnName: item.value,
          sorting: false,
          align: "center",
          width: "",
          disabled: false,
        };
      });
      this.maxAlign = this.fieldName.length - 1;
      this.delAlign = [];
    },
    //表单发布：下一步/上一步
    nextStep(flag) {
      if (flag === "plus") {
        if (this.stepNum === 1) {
          this.$refs.basicForm.validate((valid) => {
            //校验步骤一数据
            if (valid) {
              //获取表字段
              getFormInfo(this.formInfo.basic.typeId)
                .then((res) => {
                  if (res.code === 0) {
                    this.fieldName = JSON.parse(res.data.formJsonData).data.map(
                      (item) => {
                        return {
                          label: item.desc,
                          value: item.name,
                          format: item.format,
                        };
                      }
                    );
                    this.setFieldMap(JSON.parse(res.data.formJsonUser).fields)
                    // 子表单的查询配置
                    if (res.data.childFormJsonData) {
                        const childrenMsgList = JSON.parse(res.data.childFormJsonData)
                        childrenMsgList.forEach(childItem => {
                            const jsonData = JSON.parse(childItem.formJsonData).map(itemDetail => {
                                return {
                                    label: itemDetail.desc,
                                    value: itemDetail.name,
                                    format: itemDetail.format,
                                };
                            })
                            this.fieldName = [...this.fieldName, ...jsonData]
                        })
                    }
                    if (!this.formInfo.id || this.showChangeForm) {
                      //新增表单发布
                      //初始化生成步骤二和步骤三的数据
                      this.resetStep2();
                      this.resetStep3();
                    }
                  }
                })
                .catch((e) => console.log(e));
              this.stepNum++;
              this.rowDrop(); //步骤二行拖拽事件
              return true;
            } else {
              return false;
            }
          });
        } else if (this.stepNum === 2) {
          this.$refs.step2.validate((valid) => {
            //校验步骤二数据
            if (valid) {
              this.stepNum++;
              this.rowDrop2(); //步骤三行拖拽事件
            } else {
              this.$message.error("字段项名称重复，请修改");
              return false;
            }
          });
        }
      } else {
        this.stepNum--;
      }
    },
    //搜索
    searchChange() {
      this.searchFormData = reorganizationParam({name: this.searchText})
      this.page.pageNo = 1;
      this.tableLoading = true;
      this.getList();
    },
    //重置搜索
    resetSeach() {
      this.searchFormData={}
      this.searchText = "";
      this.getList();
    },
    //每页条数改变
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.page.pageNo = 1;
      this.tableLoading = true;
      this.getList();
    },
    //页码改变
    currentChange(current) {
      this.page.pageNo = current;
      this.tableLoading = true;
      this.getList();
    },
    //每页条数改变
    typeSizeChange(pageSize) {
      this.typePage.pageSize = pageSize;
    },
    //页码改变
    typeCurrentChange(current) {
      this.typePage.pageNo = current;
    },
    //每页条数改变
    configSizeChange(pageSize) {
      this.configPage.pageSize = pageSize;
    },
    //页码改变
    configCurrentChange(current) {
      this.configPage.pageNo = current;
    },
    //列名校验
    fieldNameValidator(rule, value, callback) {
      if (value !== "") {
        let names = this.listConfiguration.data.filter((item) => {
          return item.columnName === value;
        });
        if (names.length > 1) {
          callback(new Error("列名重复"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    //字段项名称校验
    fieldNameValidator2(rule, value, callback) {
      if (value !== "") {
        let names = this.tableInquire.data.filter((item) => {
          return item.checked && item.field === value;
        });
        if (names.length > 1) {
          callback(new Error("字段项名称重复"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    //排序校验
    sortValidator(rule, value, callback) {
      if (value > 2147483647) {
        callback(new Error("不能超过2147483647"));
      } else {
        callback();
      }
    },
    //功能名称校验
    funcNameValidator(rule, value, callback) {
      if (this.formInfo.id !== "" && this.funcName === value) {
        //未修改
        callback();
      } else {
        if (value.length > 50) {
          callback(new Error("功能名称长度不能超过50"));
        } else if (/^[\s\S]*.*[^\s][\s\S]*$/.test(value)) {
          getAllMenu()
            .then((res) => {
              if (res.code === 0) {
                let exsit = res.data.filter((item) => {
                  return item.name === value;
                });
                if (exsit.length > 0) {
                  callback(new Error("功能名称已存在，请修改"));
                } else {
                  callback();
                }
              }
            })
            .catch((e) => {
              console.log("查询功能名称是否存在：", e);
            });
        } else {
          callback(new Error("功能名称不能为空，且不能仅包含空格"));
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.designer {
  
  .base {
    margin-right: 10%;
    margin-left: 10%;
    margin-top: 5%;

    .el-form-item {
      margin-bottom: 40px;
    }
  }

  .el-input--mini {
    width: 80px;
  }

  .operate {
    display: flex;
    margin-top: 20px;
  }

  .configure {
    margin-top: 20px;
  }

  .inquire {
    margin-top: 20px;
  }

  .designHeader {
    display: flex;
    justify-content: space-around;
    align-items: center;

    .designStep {
      display: flex;
      justify-content: center;
      width: 100%;
      margin-left: 10%;

      .designStepItem {
        width: 33.3%;
        display: flex;
        align-items: center;
        justify-content: space-around;

        .designStepLine {
          display: inline-block;
          width: calc(100% - 110px);
          height: 2px;
        }

        .designStepIndex {
          font-size: 16px;
          color: white;
          width: 30px;
          height: 30px;
          border-radius: 50%;
          text-align: center;
          line-height: 30px;
          margin-right: 5px;
          margin-left: 5px;
          font-weight: bold;
        }

        .designStepTitle {
          font-size: 14px;
          font-weight: bold;
          width: 70px;
        }
      }
    }
  }
}
</style>
<style lang="scss">
@import "@/styles/home";
.el-button--medium{
  border-radius: 2px;
}
.el-input__inner{
  border-radius: 2px;
}
.btnList{
  position: absolute;
  top: 20px;
  right: 20px;
  .el-button--small{
    border-radius: 2px;
  }
}
.designer .el-pagination{
  padding: 20px 0;
}
.searchContent{
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    position: relative;
    .el-input__inner{
      border-radius: 2px;
    }
    .el-button {
      border-radius: 2px;
    }
  }
.list-scrollbar {
  height: calc(100vh - 42px);
  overflow: hidden;
  // border-left: 1px solid #f1e8e8;
  // border-right: 1px solid #f1e8e8;
  box-sizing: border-box;
}
.list-board {
  height: 100vh;
  width: auto;
  margin-right: 370px;
  box-sizing: border-box;
}
.designer {

  .el-table {
    box-sizing: border-box;

    &::before {
      height: 0px;
    }
  }

  .el-table--border::after,
  .el-table--group::after {
    width: 0px;
    height: 0px;
  }

  .tableInfo {
    .el-table__empty-block{
      border-bottom: 1px solid rgba(0,0,0,0.06);
      border-right: 1px solid rgba(0,0,0,0.06);
    }
    .el-table__header-wrapper th, .el-table__fixed-header-wrapper th{
      height: 48px;
    }
    .el-table__cell{
      height: 48px;
    }
    .el-table-column--selection .cell{
      padding-left: 0;
      padding-right: 0
    }
  }
  .formConfig {
    .el-form-item {
       margin: 10px 0 !important;
    }

    .el-table__cell {
      // border-bottom: 0px;
      padding: 0px;
    }

    .el-table__body-wrapper {
      margin-top: 10px;
    }
  }

  .el-dialog__body {
    padding-top: 0px;

    .el-table__cell {
      // border-bottom: 0px;
      padding: 3px 0px;
    }
  }

  // 当前行高亮颜色
  // .current-row > td {
  //   background: #b2c8df !important;
  //   // color: white;
  // }

  // 鼠标悬浮行颜色
  // tr:hover > td {
  //   background-color: #b2c8df !important;
  // }
}
</style>
